<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Libs\HttpServe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class JdCallBackController extends Controller
{
//     const app_key = "AF77656B81311761CB31C274B699A271";
//     const app_secret = "7bf7d7200eeb4414b0f03dc828dc431c";

    const JD_URL = "https://oauth.jd.com/oauth/";
    const JD_CODE_URI = "authorize";
    const JD_TOKEN_URI = "token";
    const JD_CALLBACK_URL = "http://jidong.riign.com/jd-backcall";
    
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * 回调入口
     */
    public function index(Request $request, HttpServe $serve)
    {
        if ($request->has('code')) {
            $code = $request->input('code');
            $state = explode("=", base64_decode($request->input('state')));
            // $state = [id,xx];
            $re = DB::table(TABLE_APP)->where('id', $state[1])->update(['code'=>$code]);
            if ($re) {
                return 'yes';
            } else {
                return 'no';
            }
        } else {
            return  $request->all();
        }
    }
    
    /**
     * @todo 再来一次
     * @param HttpServe $serve
     * @param unknown $id
     * @return unknown
     */
    public function getAccessToken(HttpServe $serve,$id)
    {
        $app = DB::table(TABLE_APP)->where('id', $id)->first();
        $url = self::JD_URL.self::JD_TOKEN_URI;
        $param = [
          'grant_type'=>'authorization_code',
          'code' => $app->code,
          'redirect_uri' => self::JD_CALLBACK_URL,
          'client_id' => $app->app_key,
          'client_secret'=> $app->app_secret,
          'state'=> base64_encode("id=".$id)
        ];
       
        $reText = $serve->post($url.'?'. http_build_query($param) );
        $result = json_decode($reText, true);
//         logger('[jd-back]', $result);
        if (isset($result['access_token'])) {
            $re = DB::table(TABLE_APP)->where('id', $id)->update([
                'access_token'=> $result['access_token'],
                'refresh_token'=>$result['refresh_token'],
                'authorize_time'=>Date('Y-m-d H:i:s', $result['time']),
                'expire_time' => Date('Y-m-d H:i:s', $result['time'] + $result['expires_in']),
                'backup' => $reText
            ]);
        } else {
            $re = DB::table(TABLE_APP)->where('id', $id)->update([
                'backup' => $reText
            ]);
        }
        
        
        if ($re) {
            return $result;
        } else {
            return $result;
        }    
    }
    
    /**
     * @todo test
     * @param HttpServe $serve
     * @param unknown $id
     * @return unknown
     */
    public function refreshAccessToken(HttpServe $serve,$id)
    {
        $app = DB::table(TABLE_APP)->where('id', $id)->first();
        $url = self::JD_URL.self::JD_TOKEN_URI;
        $param = [
            'grant_type'=>'refresh_token',
            'refresh_token' => $app->refresh_token,
//             'redirect_uri' => self::JD_CALLBACK_URL,
            'client_id' => $app->app_key,
            'client_secret'=> $app->app_secret,
            'state'=> base64_encode("id=".$id)
        ];
        
        $reText = $serve->post($url.'?'. http_build_query($param) );
        $result = json_decode($reText, true);
        if (!$result) {
            return json_last_error();
        }
//         logger('[jd-back]', $result);
        Log::debug("[refresh]", $result);
        if (isset($result['access_token'])) {
            $re = DB::table(TABLE_APP)->where('id', $id)->update([
                'access_token'=> $result['access_token'],
                'refresh_token'=>$result['refresh_token'],
                'authorize_time'=>Date('Y-m-d H:i:s', $result['time']),
                'expire_time' => Date('Y-m-d H:i:s', $result['time'] + $result['expires_in']),
                'backup' => $reText
            ]);
        } else {
            $re = DB::table(TABLE_APP)->where('id', $id)->update([
                'backup' => $reText
            ]);
        }
        
        
        
        if ($re) {
            return $reText;
        } else {
            return $reText;
        }
    }
    
    public function codeStart($id)
    {
        $app = DB::table(TABLE_APP)->where('id', $id)->first();
        $url = self::JD_URL.self::JD_CODE_URI;
        $param = [
            'response_type'=>'code',
            'client_id'=>$app->app_key,
            'redirect_uri'=>self::JD_CALLBACK_URL,
            'state'=> base64_encode("id=".$id)
        ];
        
        return redirect($url.'?'. http_build_query($param));
    }
    
    
}
